/*
 *  Copyright (C) 2005-2007 Renier Roth
 *  www.renier.de
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package de.renier.vdr.channel.editor.container;

import java.awt.Toolkit;
import java.util.regex.Pattern;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

/**
 * RegularExpressionTextField
 * 
 * @author <a href="mailto:editor@renier.de">Renier Roth</a>
 */
public class RegularExpressionTextField extends JTextField {

  private static final long serialVersionUID = 637274918790904249L;
  private Pattern pattern = null;

  /**
   * Constructor
   * 
   * @param expression
   */
  public RegularExpressionTextField(String expression) {
    this.pattern = Pattern.compile(expression);
  }

  protected Document createDefaultModel() {
    return new ExpressionPatternDocument();
  }

  /**
   * ExpressionPatternDocument
   * 
   * @author <a href="mailto:editor@renier.de">Renier Roth</a>
   */
  class ExpressionPatternDocument extends PlainDocument {

    private static final long serialVersionUID = 1968670819471012330L;

    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
      // get text and apply change temp
      StringBuffer tempChange = new StringBuffer();
      tempChange.append(RegularExpressionTextField.this.getText());
      tempChange.insert(offs, str);
      // know check regular expression
      if (RegularExpressionTextField.this.pattern.matcher(tempChange.toString()).matches()) {
        // insert if reg expression is valid
        super.insertString(offs, str, a);
      } else {
        // peep if not right, dont store changes
        Toolkit.getDefaultToolkit().beep();
      }
    }
  }
}